﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.MediaCenter.UI;
using System.Diagnostics;
using MyMoviesBrowserLibrary;
//using Toub.MediaCenter.Dvrms.Metadata;

namespace MyMoviesBrowser
{
    public class SeriesGallery : GalleryPage
    {
        private TVSeries currentSeries;
        public TVSeries CurrentSeries
        {
            get { return currentSeries; }
            set
            {
                if (currentSeries != value)
                {
                    currentSeries = value;
                    FirePropertyChanged("CurrentSeries");
                }
            }
        }

        List<TVSeries> series = new List<TVSeries>();

        public SeriesGallery(List<Series> seriesList)
        {
            ItemSize = GalleryItemSize.Large;
            Description = "TV Series";
            foreach (Series xseries in seriesList)
            {
                series.Add(new TVSeries(xseries));
            }
            
            VirtualList galleryList = new VirtualList(this, null);
            galleryList.EnableSlowDataRequests = true;
            galleryList.RequestSlowDataHandler = new RequestSlowDataHandler(CompleteGalleryItem);
            Content = galleryList;

            CreateGalleryFilters();
        }

        private void CreateGalleryFilters()
        {
            //
            // Put together a list of filters on the content.
            //

            ArrayListDataSet list = new ArrayListDataSet(this);

            // Create the unfiltered "All" filter
            ModelItem filter = new Filter(this, Resources.GroupBy_Title, 0);

            foreach (TVSeries s in series)
                this.Content.Add(CreateGalleryItem(s, "", false));
        }

        private ThumbnailCommand CreateGalleryItem(TVSeries seriesData, string description, bool isHeading)
        {
            ThumbnailCommand item = new ThumbnailCommand(this);
            item.Description = seriesData.Series.SeriesName;
            item.Data = seriesData;
            item.ShowHeading = isHeading;

            item.Metadata = description;

            item.Invoked += delegate(object sender, EventArgs args)
            {
                ThumbnailCommand galleryItem = (ThumbnailCommand)sender;
                Application.Current.GoToGalleryPage(new SeasonGallery(((TVSeries)galleryItem.Data).Series));
            };

            item.OnFocus += delegate(object sender, EventArgs args)
            {
                ThumbnailCommand galleryItem = (ThumbnailCommand)sender;

                SeriesGallery page = (SeriesGallery)galleryItem.Owner;
                page.CurrentSeries = (TVSeries)galleryItem.Data;
            };

            return item;
        }

        public override int JumpTo(string searchText)
        {
            searchText = searchText.ToLower();
            List<TVSeries> temp = null;
            do
            {

                temp = (from m in series
                        where m.Series.OrderName.ToLower().StartsWith(searchText)
                        select m).ToList();
                if (searchText.Length > 0)
                    searchText = searchText.Substring(0, searchText.Length - 1);
            } while (temp.Count == 0 && searchText.Length > 0);

            if (temp.Count > 0)
            {
                int i = series.IndexOf(temp.First());
                return i;
            }
            return -1;
        }

        #region slowdatahandlers
        /// <summary>
        /// Finishes any slow data for a gallery item.
        /// </summary>
        protected void CompleteGalleryItem(VirtualList list, int index)
        {
            ThumbnailCommand item = (ThumbnailCommand)list[index];
            CompleteGalleryItem(item, (TVSeries)item.Data);
        }

        /// <summary>
        /// Finishes any slow data for a gallery item.
        /// </summary>
        protected void CompleteGalleryItem(ThumbnailCommand item, TVSeries seriesData)
        {
            string imageName = "file://" + seriesData.Series.FolderImage;
            item.Image = LoadImage(imageName);
        }
        #endregion

        //void AddRecordedToSeries(string filePath)
        //{
        //    using (DvrmsMetadataEditor editor = new DvrmsMetadataEditor(filePath))
        //    {
        //        IDictionary meta = editor.GetAttributes();

        //        string seriesTitle = ((MetadataItem)meta[MetadataEditor.Title]).Value.ToString();

        //        Series rSeries = series.FirstOrDefault(s => s.Name == seriesTitle && s.IsRecording == true);
        //        if (rSeries == null)
        //        {
        //            rSeries = new Series();
        //            rSeries.Name = seriesTitle;
        //            rSeries.IsRecording = true;
        //            //rSeries.FolderImage = 

        //            rSeries.SortName = rSeries.Name;
        //            if (rSeries.SortName.ToLower().StartsWith("the "))
        //                rSeries.SortName = rSeries.SortName.Substring(4) + ", The";

        //            series.Add(rSeries);

        //            Season season = new Season();
        //            season.Series = rSeries;
        //            rSeries.Seasons = new List<Season>() { season };

        //            season.Episodes = new List<Episode>();
        //        }

        //        Season rSeason = rSeries.Seasons.First();

        //        Episode rEpisode = new Episode();
        //        rEpisode.Name = ((MetadataItem)meta[MetadataEditor.Subtitle]).Value.ToString();
        //        rEpisode.Overview = ((MetadataItem)meta[MetadataEditor.SubtitleDescription]).Value.ToString();
        //        try
        //        {
        //            rEpisode.DateAdded = DateTime.Parse(((MetadataItem)meta["WM/MediaOriginalBroadcastDateTime"]).Value.ToString());
        //        }
        //        catch 
        //        {
        //            rEpisode.DateAdded = File.GetLastWriteTime(filePath);
        //        }

        //        rEpisode.MediaFile = new MediaFile() { FileName = Path.GetFileName(filePath), Path = filePath, Played = MyMoviesBrowserBusiness.CheckWatched(filePath) };

        //        rSeason.Episodes.Add(rEpisode);
        //    }
        //}
    }
}
